package org.xhy.ruleengine.utils;

import org.springframework.util.ClassUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @Author: Xhy
 * @CreateTime: 2024-06-23 22:05
 */
public class BeanUtils {

    public static Map<String, Object> convertToMap(Object object) {
        Map<String, Object> map = new HashMap<>();
        convertObjectToMap(object, object.getClass().getSimpleName().toLowerCase(), map);
        return map;
    }
    private static void convertObjectToMap(Object object, String prefix, Map<String, Object> map) {
        if (object == null) {
            return;
        }

        Class<?> clazz = object.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String fieldName = prefix.isEmpty() ? field.getName() : prefix + "." + field.getName();
            try {
                Object fieldValue = field.get(object);
                if (fieldValue != null && ClassUtils.isPrimitiveOrWrapper(field.getType()) || field.getType().equals(String.class)) {
                    map.put(fieldName, fieldValue);
                } else {
                    convertObjectToMap(fieldValue, fieldName, map);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
